package 热题100.图论.岛屿数量_200_中等;

import java.util.Deque;
import java.util.LinkedList;

/*
给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外，你可以假设该网格的四条边均被水包围。

示例 1：
输入：grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
输出：1

示例 2：
输入：grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
输出：3

提示：

m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] 的值为 '0' 或 '1'

思路:
    一眼bfs，注意：先遍历岛屿，第一个不为0的岛屿数量就+1，bfs是搜索与该岛屿相邻的陆地，并标记为看过。
* */
public class Solution {
    public static void main(String[] args) {
        char[][] grid = {
                {'1', '1', '0', '0', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '1', '0', '0'},
                {'0', '0', '0', '1', '1'} };
        System.out.println(numIslands(grid));
    }
    static int[][] f = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
    static boolean[][] flag;
    public static int numIslands(char[][] grid) {
        int ans = 0;
        flag = new boolean[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i ++){
            for (int j = 0; j < grid[0].length; j ++){
                if (!flag[i][j] && grid[i][j] == '1'){
                    ans ++;
                    flag[i][j] = true;
                    bfs(flag, grid, i, j);
                }
            }
        }
        return ans;
    }
    static void bfs(boolean[][] flag, char[][] grid, int x, int y){
        Deque<int[]> deque = new LinkedList<>();
        deque.offer(new int[]{x, y});
        while (!deque.isEmpty()){
            int[] t = deque.peek();
            deque.poll();
            for (int i = 0; i < 4; i ++){
                int dx = f[i][0] + t[0], dy = f[i][1] + t[1];
                if (dx >= 0 && dx < grid.length && dy >= 0 && dy < grid[0].length){
                    if (!flag[dx][dy] && grid[dx][dy] == '1'){
                        flag[dx][dy] = true;
                        deque.offer(new int[]{dx, dy});
                    }
                }
            }
        }
    }
}
